package org.hank.compose_yyzs.ui.screen

import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.Button
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.ramcosta.composedestinations.navigation.EmptyDestinationsNavigator
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.hank.compose_yyzs.R
import org.hank.compose_yyzs.bean.UnUploadFile
import org.hank.compose_yyzs.bean.UnUploadInfo
import org.hank.compose_yyzs.ui.animations.AnimatedLazyListItem
import org.hank.compose_yyzs.ui.animations.widgets.AnimatedLazyColumn
import org.hank.compose_yyzs.ui.theme.AppTheme
import org.hank.compose_yyzs.utils.getString
import org.hank.compose_yyzs.viewmodel.UploadFileViewModel

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 *@auth: Hank
 *邮箱: cs16xiaoc1@163.com
 *创建时间: 2023/9/14 9:51
 *描述:
 */


@OptIn(ExperimentalFoundationApi::class)
@Destination
@Composable
fun UploadFileScreen(navigation: DestinationsNavigator) {
    var pagers = listOf(
        getString(resourceId = R.string.upload_unup),
    )
    var pagerState =
        rememberPagerState(initialPage = 0, initialPageOffsetFraction = 0f) { pagers.size }
    var viewModel: UploadFileViewModel = hiltViewModel()
    var scope = rememberCoroutineScope()
    var lifecycleOwner = LocalLifecycleOwner.current
    var unUploadInfo = viewModel.allFiles.collectAsStateWithLifecycle()
    var state = rememberLazyListState()

    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_RESUME) {
                scope.launch {
                    viewModel.loadDefaultUploadFile()
                    delay(500)
                    viewModel.getAllUnUploadFile()
                }
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }

    LaunchedEffect(Unit) {

    }


    Column(
        modifier = Modifier
            .fillMaxSize()
    ) {
        Surface(shadowElevation = 4.dp) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(color = AppTheme.colors.mainColor)
            ) {
                Box(modifier = Modifier.fillMaxWidth()) {
                    Image(
                        painter = painterResource(id = R.mipmap.ic_return_black),
                        contentDescription = "",
                        modifier = Modifier
                            .align(Alignment.CenterStart)
                            .padding(16.dp)
                            .clickable(
                                indication = null,
                                onClick = { navigation.popBackStack() },
                                interactionSource = remember { MutableInteractionSource() })
                    )
                    Row(
                        modifier = Modifier
                            .align(Alignment.Center)
                            .padding(top = 16.dp, bottom = 16.dp)
                    ) {
                        Text(
                            getString(R.string.upload),
                            style = MaterialTheme.typography.titleLarge,
                        )
                        Text(
                            text = "(0/0)",
                            style = MaterialTheme.typography.titleLarge.copy(color = AppTheme.colors.textSecondary)
                        )
                    }
                }
                Divider(color = AppTheme.colors.divider, thickness = 1.dp)
            }
        }

        ScrollableTabRow(selectedTabIndex = pagerState.currentPage, edgePadding = 0.dp) {
            pagers.forEachIndexed { index, s ->
                Tab(
                    text = {
                        Text(
                            text = s,
                            style = MaterialTheme.typography.bodyMedium.copy(color = AppTheme.colors.textPrimary)
                        )
                    }, selected = pagerState.currentPage == index, onClick = {
                        scope.launch {
                            pagerState.animateScrollToPage(index)
                        }
                    })
            }
        }
        Divider(modifier = Modifier.height(1.dp))
        HorizontalPager(state = pagerState) {
            Column {
                Row {
                    Button(onClick = { viewModel.selectAll() }) {
                        Text(text = "SelectAll")
                    }
                    Spacer(modifier = Modifier.width(4.dp))
                    Button(onClick = { viewModel.delSelectFiles() }) {
                        Text(text = "DelSelect")
                    }
                    Spacer(modifier = Modifier.width(4.dp))
                    Button(onClick = {
                        scope.launch {
                            viewModel.loadDefaultUploadFile()
                            delay(500)
                            viewModel.getAllUnUploadFile()
                        }
                    }) {
                        Text(text = "Reset")
                    }
                }
                AnimatedLazyColumn(
                    state = state,
                    modifier = Modifier.fillMaxSize(),
                    items = unUploadInfo.value.map {
                        AnimatedLazyListItem(key = it.id.toString(), value = it.projectName) {
                            UploadItem(it) {
                                viewModel.selectItem(it)
                            }
                            Spacer(modifier = Modifier.height(8.dp))
                        }
                    })
            }
        }
    }
}

@Composable
fun UploadItem(unuploadInfo: UnUploadInfo, onFileSelect: (UnUploadFile) -> Unit) {
    Column(modifier = Modifier.animateContentSize()) {
        Text(text = unuploadInfo.projectName, style = MaterialTheme.typography.titleLarge)
        Text(text = unuploadInfo.projectName, style = MaterialTheme.typography.bodyMedium)
        repeat(unuploadInfo.files.size) {
            UploadSubItem(unuploadInfo.files[it], onFileSelect)
        }
    }
}

@Composable
fun UploadSubItem(unuploadFile: UnUploadFile, onFileSelect: (UnUploadFile) -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 8.dp, bottom = 8.dp)
            .background(AppTheme.colors.mainColor)
    ) {
        RadioButton(selected = unuploadFile.isSelected, onClick = {
            onFileSelect.invoke(unuploadFile)
        })
        Spacer(modifier = Modifier.width(16.dp))
        Text(
            text = String.format(
                getString(resourceId = R.string.upload_unuploadfile_station_format),
                unuploadFile.stationId
            )
        )
        Spacer(modifier = Modifier.weight(1f))
        Text(
            text = unuploadFile.fileCreateTime,
            style = MaterialTheme.typography.bodyMedium.copy(color = AppTheme.colors.textSecondary)
        )
    }
}

@Preview
@Composable
fun UploadPrev() {
    AppTheme {
        UploadFileScreen(EmptyDestinationsNavigator)
    }
}